﻿using Sc.Cache;
using Sc.Domain;
using Sc.Persistence;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sc.Service
{
    public class UserService
    {
        /// <summary>
        /// 待办事宜
        /// </summary>
        private readonly Sys_ToDoListDAO dao = new Sys_ToDoListDAO();
        /// <summary>
        /// 用户登录(手机端)
        /// </summary>
        /// <param name="userCode">登录账号</param>
        /// <param name="userPwd">登录密码</param>
        /// <param name="token">手机唯一编码</param>
        /// <param name="osType">系统类型</param>
        /// <returns></returns>
        public UserLogin UserLoginForApp(string userCode, string userPwd, string token,int osType)
        {
            Sys.SysWebservice sys = CommService.IntanceSys();
            var pwd = Encrypt.EncryptByMD5(userPwd);
            var user = sys.ZcmsUserLogin(userCode, pwd);
            ProjectCache.UserToken.Clear();
            if (user != null && user.Id > 0)
            {
                if (ProjectCache.UserToken.ContainsKey(user.Id))
                {
                    var ent = ProjectCache.UserToken[user.Id];
                    if (ent.Token != token)
                    {
                        UserToken tk = new UserToken() { UserId = user.Id, OsType = osType, Token = token };
                        new UserTokenService().SaveData(tk);
                    }
                }
                else
                {
                    UserToken tk = new UserToken() { UserId = user.Id, OsType = osType, Token = token };
                    new UserTokenService().SaveData(tk);
                }
                var pid = Convert.ToInt32(ConfigurationManager.AppSettings["pid"]);
                var gl = Convert.ToInt32(ConfigurationManager.AppSettings["gl"]);
                var pt = Convert.ToInt32(ConfigurationManager.AppSettings["pt"]);
                var lu = sys.LoadUserPerimissionsById(new Sys.Users() { Id = user.Id }, gl);
                var ul = sys.LoadUserPerimissionsById(new Sys.Users() { Id = user.Id }, pid);
                var tp = sys.LoadUserPerimissionsById(new Sys.Users() { Id = user.Id }, pt);
                var tmp = string.Empty;
                if (tp.PermissionList != null && tp.PermissionList.Length > 0)
                {
                    tmp = "1,";
                }
                if (ul.PermissionList != null && ul.PermissionList.Length > 0)
                {
                    tmp = "2,";
                }
                if (lu.PermissionList != null && lu.PermissionList.Length > 0)
                {
                    tmp += "3,";
                }
                if (string.IsNullOrEmpty(tmp))
                {
                    tmp = "1,";
                }
                tmp = tmp.Remove(tmp.LastIndexOf(','));
                return new UserLogin() { UserId = user.Id, UserName = user.Name, OrgzNo = user.MainOrgz, IsDriver = tmp };
            }
            return null;
        }
        /// <summary>
        /// 用户登录(PC端)
        /// </summary>
        /// <param name="userCode">登录账号</param>
        /// <param name="userPwd">登录密码</param>
        /// <returns></returns>
        public UserLogin UserLoginForPc(string userCode, string userPwd)
        {
            Sys.SysWebservice sys = CommService.IntanceSys();
            var pwd = Encrypt.EncryptByMD5(userPwd);
            var user = sys.ZcmsUserLogin(userCode, pwd);
            if (user != null && user.Id > 0)
            {
                ProjectCache.ClearCardInfo();
                return new UserLogin() { UserId = user.Id, UserName = user.Name, OrgzNo = user.MainOrgz };
            }
            return null;
        }

        /// <summary>
        /// 获取事故申请列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="pageIndex">当前第几页</param>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public CommModel<MyRequest> GetList(int userId, int pageSize, int pageIndex,int type)
        {
            Hashtable param = new Hashtable();
            string where = "AND UserId=" + userId;
            if (type > 0)
                where += " AND Type=" + type;
            param.Add("A1", pageIndex);
            param.Add("A2", pageSize);
            param.Add("A3", where);
            param.Add("A4", "VW_MyRequests");
            param.Add("A5", "igtime desc");
            var ht = CommDAO.CommPagination(param);
            if (Convert.ToInt32(ht["record"]) > 0)
            {
                DataTable dt = ht["data"] as DataTable;
                List<MyRequest> list = new List<MyRequest>();
                foreach (DataRow item in dt.Rows)
                {
                    list.Add(DataRowToModel(item));
                }
                CommModel<MyRequest> ent = new CommModel<MyRequest>();
                ent.Data = list;
                ent.PageCount = Convert.ToInt32(ht["PageCount"]);
                ent.RecordCount = Convert.ToInt32(ht["record"]);
                return ent;
            }
            return null;
        }
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public MyRequest DataRowToModel(DataRow row)
        {
            MyRequest model = new MyRequest();
            if (row != null)
            {
                if (row["Id"] != null && row["Id"].ToString() != "")
                {
                    model.Id = row["Id"].ToString();
                }
                if (row["Type"] != null && row["Type"].ToString() != "")
                {
                    model.Type = int.Parse(row["Type"].ToString());
                }
                if (row["Title"] != null && row["Title"].ToString() != "")
                {
                    model.Title = row["Title"].ToString();
                }
                if (row["igtime"] != null && row["igtime"].ToString() != "")
                {
                    model.Igtime = Convert.ToDateTime(row["igtime"].ToString());
                }
            }
            return model;
        }
        /// <summary>
        /// 密码修改
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        public int UpdatePassword(int userId,string pwd)
        {
            Sys.SysWebservice sys = CommService.IntanceSys();
            var upwd = Encrypt.EncryptByMD5(pwd);
            return sys.UpdatePassword(userId, upwd);
        }

        /// <summary>
        /// 获取用户所有
        /// </summary>
        /// <param name="userId">当前用户ID</param>
        /// <returns></returns>
        public dynamic GetUserPermission(int userId)
        {
            Sys.SysWebservice sys = CommService.IntanceSys();
            Sys.Users ent = new Sys.Users() { Id = userId };
            var perimission = sys.LoadUserPerimissions(ent);
            var data = from a in perimission.PermissionList
                       select new
                       {
                           Id = a.PermissionNo.Id
                       };
            return data;
        }
    }
}
